package calculator.rpn.engine.impl;

import calculator.rpn.api.CalculatorService;
import calculator.rpn.engine.Calculator;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.stream.Stream;

public class DefaultCalculatorService implements CalculatorService {
    private final static int DISPLAY_SCALE = 10;


    private Calculator calculator = new RPNCalculator();
    @Override
    public void onInput(String input) {
        if(!StringUtils.isBlank(input)) {
            Stream.of(input.split("[ \t]+")).forEach(str -> calculator.append(str.trim().toLowerCase()));
        }
    }

    @Override
    public String calculate() {
        BigDecimal result = calculator.calculate();

        BigDecimal displayResult = new BigDecimal(result.toString())
                .setScale(DISPLAY_SCALE, RoundingMode.FLOOR).stripTrailingZeros();

        return displayResult.toPlainString();
    }

    @Override
    public void appendStateTo(StringBuilder sb) {
        calculator.appendSummary(sb, DISPLAY_SCALE);
    }
}
